﻿define('viewModel', ['logger', 'loc'], function (logger, loc) {

    function addListBehavior(self, dao, entityConstructor) {
        self.items = ko.observableArray([]),
        self.isLoading = ko.observable(false);
        self.loadItems = function (callback) {
            self.isLoading(true);
            dao.getAll(function (error, result) {
                if (error) {
                    logger.error(error, true);
                } else {
                    self.items.removeAll();
                    result.forEach(function (item) {
                        self.items.push(new entityConstructor(item));
                    });
                }
                self.isLoading(false);
                callback();
            }, self);
        };
        self.deleteItem = ko.asyncCommand({
            execute: function (callback) {
                var s = this;
                if (!confirm(loc.DeleteConfirm)) {
                    callback();
                    return;
                }
                s.isDeleting(true);
                dao.del(s.Id, function (error) {
                    if (error) {
                        logger.error(error, true);
                        callback();
                    } else {
                        self.loadItems(function () {
                            callback();
                        });
                    }
                    s.isDeleting(false);
                });
            }
        });
    }

    function addEditItemBehavior(self, newTitle, editTitle, dao, entityConstructor, afterSaveAction) {
        self.title = newTitle;
        self.item = null;
        self.start = function(params, bind) {
            if (!params.id) {
                var item = new entityConstructor();
                this.item = item;
                bind();
            } else {
                self.title = editTitle;
                dao.find(params.id, function(error, result) {
                    if (error) {
                        logger.error(error, true);
                    } else {
                        self.item = new entityConstructor(result);
                        bind();
                    }
                });
            }
        };

        self.save = ko.asyncCommand({
            execute: function(callback) {
                ko.validation.group(self.item).showAllMessages(true);
                if (!self.item.isValid()) {
                    callback();
                } else {
                    dao.save(self.item, function(error) {
                        callback();
                        if (error) {
                            logger.error(error, true);
                        } else {
                            afterSaveAction();
                        }
                    });
                }
            }
        });
    }

    return {
        addListBehavior: addListBehavior,
        addEditItemBehavior: addEditItemBehavior
    };
});